package flow

import (
	"fmt"

	"xtsec.com/dns-syncer/client"
	"xtsec.com/dns-syncer/common"
	"xtsec.com/dns-syncer/common/email"
	"xtsec.com/dns-syncer/common/ip"
	"xtsec.com/dns-syncer/common/tools"
)

var ipFileName = "ip.txt"

func Sync(dnsSyncClient client.Interface) {
	ip, err := ip.Get()
	if err != nil {
		fmt.Printf("get public ip error:  %v\n", err)
		return
	}

	recoredIp, err := tools.ReadFile(ipFileName, true)
	if err != nil {
		fmt.Printf("read ip file error:  %v\n", err)
		return
	}

	if recoredIp == ip {
		fmt.Printf("public ip is not change:  %v\n", ip)
		return
	}

	updated, err := dnsSyncClient.Start(ip)
	if err != nil {
		fmt.Printf("sync %s dns parse record error:  %v\n", dnsSyncClient.Name(), err)
		return
	}

	if updated {
		fmt.Printf("sync %s dns parse record success. current ip: %s\n\n", dnsSyncClient.Name(), ip)
	}

	// 记录ip
	if err := tools.WriteFile(ipFileName, ip); err != nil {
		fmt.Printf("record ip file error:  %v\n", err)
		return
	}

	// 发送邮件
	setting := common.GetSetting()
	email := email.NewEmail(setting.Email.Host, setting.Email.Port, setting.Email.From, setting.Email.Password, setting.Email.To)
	if err := email.Send("桂语听澜ip变更提醒", fmt.Sprintf("ip: %s", ip)); err != nil {
		fmt.Printf("send email error: %s", err.Error())
	}
}
